<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 1. 列表数据数组
        const listArr = [
            {id: '1', name: '安徽省', pid: ''},
            {id: '2', name: '合肥市', pid: '1'},
            {id: '3', name: '黄山市', pid: '1'},
            {id: '4', name: '广州省', pid: ''},
            {id: '5', name: '广东市', pid: '4'},
            {id: '6', name: '深圳市', pid: '4'},
            {id: '7', name: '河北省', pid: ''},
            {id: '8', name: '山东省', pid: ''}
        ]

        function transListToTreeArr(list, flag){
            // 1. 定义一个数组
            const treeArr = []
            // 2. 遍历列表数组
            list.forEach((item)=>{
                // 2.1 判断
                if (item.pid === flag){
                    // item => 一级
                    // 一级部门是可能有二级部门, 所有我们要拿一级部门的id作为查找标记
                    // resArr 二级部门数组
                    const resArr = transListToTreeArr(list, item.id)
                    if(resArr.length > 0){
                        item.children = resArr
                    }
                    treeArr.push(item)
                }
            })

            // 3. 返回树形数组
            return treeArr
        }

        const treeArr = transListToTreeArr(listArr, '')
        console.log(treeArr)
    </script>
</body>
</html>